今天是單純的js練習,以及題目截圖
以及個人codepen
以下為基礎的陣列方法操作運用
const food = ["rice", "banana", "apple", "hotDog"];
// 建立一個資料陣列
function isRice(food, index, foodArr) {
return food === "rice";
}
// 建立一個callBack函式
const onlyRice = food.filter(isRice);
// 將陣列篩選後,回傳條件符合rice的陣列 ["rice"]
const food = ["rice", "banana", "apple", "hotDog"];
food.filter((food, index, foodArr) => {
return food === "cola";
});
// 預期會是一個空陣列 []
const numbers = [1, 2, 3];
// 創建一個數字陣列
const doubles = numbers.map(function (num, index, currentArray) {
return num * 2;
});
// [2, 4, 6];
將此陣列進行map運算,將每一個數字都乘於2之後,回傳新的數字陣列
const numbers = [1, 2, 3];
const nothing = numbers.map(function (num, index, currentArray) {
return;
});
console.log(nothing); // [undefined, undefined, undefined]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
結果為 [1, 100000, 21, 30, 4]
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function (a, b) {
console.log("a:",a, "b:", b)
return a - b;
});
// 以下為console.log打印出每次a和b的結果
a: 2 b: 4
a: 5 b: 2
a: 5 b: 4
a: 1 b: 4
a: 1 b: 2
a: 3 b: 4
a: 3 b: 2
console.log(numbers); // [1, 2, 3, 4, 5]
numbers.sort(function (a, b) {
return b - a;
});
console.log(numbers); // [5, 4, 3, 2, 1]
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
];
const result5 = inventors.sort((a, b) => (a.passed - a.year) - (b.passed - b.year));
回傳一個數字,用來表示其與被比較的字串的先後順序。
用來搭配sort就可以輕鬆的將字串做排序.
const abcd = ["c", "a", "d", "b"];
const sortArr = abcd.sort(); // ['a', 'b', 'c', 'd']
const sortArr = abcd.sort((a, b) => {
return a.localeCompare(b, "en");
})
console.log(sortArr); // ['a', 'b', 'c', 'd']
const num = ["9", "3", "6", "2", "1"];
const sortNum = num.sort((a, b) => {
return a.localeCompare(b, undefined, {numeric: true});
})
console.log(sortNum); // ["1","2","3","6","9"]
使用上很難操作一個方法,至今用還是會卡卡哈哈,腦袋總是轉不過來
const num = [1, 2, 3, 4, 5];
const total = num.reduce((acc, cur) => acc + cur, 0); // 15
const num = [1, 2, 3, 4, 5];
const total = num.reduce((acc, cur) => acc + cur); // 15
var flattened = [
[0, 1],
[2, 3],
[4, 5],
];
flattened.reduce((acc, cur) => {
return [...acc, ...cur];
}); // [0, 1, 2, 3, 4, 5]
flattened.flatMap((el) => el); // [0, 1, 2, 3, 4, 5]
js的基礎用法博大精深,有些用法也是看過別人的寫法後,才驚覺原來這個方法可以這樣用啊!!!突然新世界打開哈哈.
語法很多,只能有空看到什麼學什麼了,學了忘了就去查MDN文件吧XD